<?php
/**
 *
 */
class userModel extends Model
{
    public function getOneById($id, $field = '')
    {
        return $this->field($field)->selectOne(array('id' => intval($id)));
    }
    public function coin($user_id, $coin = false)
    {
        $user_id = intval($user_id);
        if (!$user_id) {
            return false;
        }
        fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/UserRedisService.php');
        $user_redis = new UserRedisService();
        if ($coin === false) {
            return $user_redis->getOne_db($user_id, 'coin');
        } else {
            $coin  = intval($coin);
            $where = array('id' => $user_id);
            if ($coin < 0) {
                $where['coin'] = array('>=', -$coin);
            }
            $res = $this->update(array('coin' => array('coin + ' . $coin)), $where);
            if ($res) {
                $user_redis->inc_field($user_id, 'coin', $coin);
            }
            return $res;
        }
    }
    public function multiAddCoin($game_log_id, $result, $times)
    {
        $table      = DB_PREFIX . 'user_game_log';
        $table_user = DB_PREFIX . 'user';
        self::$sql  =
            "UPDATE $table_user AS a
                INNER JOIN (
                    SELECT
                        SUM(`money`) AS `win`,
                        `user_id`
                    FROM
                        $table
                    WHERE
                        `game_log_id` = $game_log_id
                    AND `bet` = $result
                    GROUP BY
                        `user_id`
                ) AS b ON a.id = b.user_id
                SET a.coin = a.coin + b.win * $times";
        return Connect::exec(self::$sql);
    }
    public function returnCoin($game_log_id)
    {
        $table      = DB_PREFIX . 'user_game_log';
        $table_user = DB_PREFIX . 'user';
        self::$sql  =
            "UPDATE $table_user a
            INNER JOIN (
                SELECT
                    SUM(`money`) AS `win`,
                    `user_id`
                FROM
                    $table
                WHERE
                    `game_log_id` = $game_log_id
                GROUP BY
                    `user_id`
            ) AS b ON a.id = b.user_id
            SET a.coin = a.coin + b.win";
        return Connect::exec(self::$sql);
    }
}
